/**********
@name: thumb组件
@describtion: 提供缩略图上传策略，可以接收一个图片数组其中选择，还可以在素材库中选择 并且进行裁剪
@author:liubingye
@date:2023-03-09 16:02:45
***********/
<template>
  <div class="thumb-outer-box">
    <div class="editor-icon" v-if="props.children && props.children.length > 0" @click="changeChildrenShow">
      <span :class="{ plus: childrenShow }"></span>
    </div>
    <el-form-item :prop="props.field">
      <div class="thumb-img-box" @click="handleShowThumbBox" :class="'thumb-img-box-' + props.setting.picture_scale">
        <div v-if="thumbImg" class="delete-thumb" @click.stop="deleteThumb">
          <el-icon>
            <Delete />
          </el-icon>
        </div>
        <img v-if="thumbImg" :src="thumbImg" alt="">
        <el-icon v-else>
          <Plus />
        </el-icon>
      </div>
    </el-form-item>
    <el-dialog v-model="showThumbBox" :title="props.title + '选择'" width="944px" class="thumb-tool-box"
      @close="handleCloseThumbBox" @open="handleOpenThumbBox">
      <div class="image-choose-content">
        <div class="image-choose-step1" v-if="thumbStep === 1">
          <el-tabs v-model="thumbSelectMenu" class="thumb-tabs" @tab-change="handleTabChange">
            <el-tab-pane :label="grabField.name + '图片'" v-if="grabField" name="1">
              <div class="inner-image-choose">
                <h3>从{{ grabField.name }}中选择图片：</h3>
                <el-scrollbar height="432px">
                  <div class="thumb-list-box" v-if="thumbList.length > 0">
                    <div class="thumb-item" v-for="item in thumbList" :key="item.id" @click="chooseThumb(item)">
                      <el-checkbox class="thumb-item-checkbox"
                        :model-value="choseThumb[0].id === item.id"></el-checkbox>
                      <img :src="item.url" alt="">
                    </div>
                  </div>
                  <div class="no-data" v-else>
                    <el-empty :description="grabField.name + '暂无图片'" />
                  </div>
                </el-scrollbar>
              </div>
            </el-tab-pane>
            <el-tab-pane label="本地上传" name="2">
              <div class="inner-image-choose">
                <el-upload v-model:file-list="imgUploadList" class="uploader-content"
                  :before-upload="handleBeforeUpload" :http-request="handleUpload" :show-file-list="false"
                  accept="image/png, image/jpeg" :limit="1" :on-change="handleChangeFiles" :on-exceed="handleExceed"
                  drag>
                  <div class="upload-img-box">
                    <div v-for="(element, index) in imgUploadList" :key="index">
                      <li>
                        <div class="img-box">
                          <img :src="element.url" alt="">
                        </div>
                        <div class="progress-box" v-show="element.percentage !== 100">
                          <el-progress :percentage="element.percentage"
                            :status="element.status === 'success' ? 'success' : ''" :stroke-width="20"
                            :text-inside="true" />
                        </div>
                        <div class="remove-upload" @click.stop="removeUpload(element.uid)">
                          <el-icon>
                            <Delete />
                          </el-icon>
                        </div>
                      </li>
                    </div>
                    <p class="no-upload-list" v-if="imgUploadList && imgUploadList.length < 1">
                      <i class="iconfont" style="font-size: 48px;margin-bottom: 10px;">&#xe65c;</i><br>
                      <span>暂未上传图片，请点击或拖拽“上传图片”</span>
                    </p>
                  </div>
                </el-upload>
              </div>
            </el-tab-pane>
            <el-tab-pane label="素材库" name="3">
              <div class="inner-image-choose">
                <div class="material-choose-box" @click.stop="changeLibrary">
                  <div class="btn" :class="{ 'is-active': materialQuery.path === 'public' }" path="public">公共库</div>
                  <div class="btn" :class="{ 'is-active': materialQuery.path === 'content' }" path="content">内容库</div>
                  <div class="btn" :class="{ 'is-active': materialQuery.path === 'template' }" path="template">模板库</div>
                </div>
                <div class="thumb-list-box" v-if="materialImages.length > 0">
                  <div class="thumb-item" v-for="item in materialImages" :key="item.id" @click="chooseMaterial(item)">
                    <el-checkbox class="thumb-item-checkbox"
                      :model-value="choseMaterialThumb[0].id === item.id"></el-checkbox>
                    <img :src="item.url" alt="">
                  </div>
                </div>
                <div v-else>
                  <el-empty description="暂无图片" />
                </div>
                <PaginationViewSimple :total="materialQuery.total" :pageSize="materialQuery.pageSize"
                  :currentPage="materialQuery.currentPage" @currentChange="handleMaterialCurrentChange" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="image-choose-step2" v-if="thumbStep === 2">
          <div class="cropper-box">
            <div class="cropper">
              <vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType"
                :autoCrop="true" :fixed-number="imageScale" :fixed="true" autoCropWidth="10000" autoCropHeight="10000"
                mode="contain" :full="true" :centerBox="true" :infoTrue="true" @realTime="thumbPreview"></vueCropper>
            </div>
            <div class="cropper-option">
              <el-icon @click="changeScale(1)">
                <ZoomIn />
              </el-icon>
              <el-icon @click="changeScale(-1)">
                <ZoomOut />
              </el-icon>
            </div>
          </div>
          <div class="thumb-preview" v-if="props.setting.picture_scale === 1">
            <p>封面裁剪</p>
            <div class="inner-thumb-preview">
              <div class="thumb-preview-item big-preview">
                <div class="img-box">
                  <div :style="previewStyle">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img">
                    </div>
                  </div>
                </div>
                <div class="img-msg">
                  <p>新闻封面（16:9）</p>
                  <span>该内容在列表页中，将显示此类型封面缩略图</span>
                </div>
              </div>
              <div class="thumb-preview-item small-preview">
                <div class="img-box">
                  <div :style="previewStyle" style="transform: translateX(-13%);">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img">
                    </div>
                  </div>
                </div>
                <div class="img-msg">
                  <p>新闻封面（4:3）</p>
                  <span>该内容在部分模板中，将显示此类型封面缩略图</span>
                </div>
              </div>
            </div>
          </div>
          <div class="thumb-preview" v-if="props.setting.picture_scale === 2">
            <p>图片裁剪</p>
            <div class="inner-thumb-preview">
              <div class="thumb-preview-item">
                <div class="img-box">
                  <div :style="previewStyle">
                    <div :style="previewImg.div">
                      <img :src="previewImg.url" :style="previewImg.img">
                    </div>
                  </div>
                </div>
              </div>
              <div class="img-msg">
                <p>图片比例（3:4）</p>
              </div>
            </div>
          </div>
        </div>
        <div class="footer-btn-box">
          <div class="inner-footer">
            <div class="left-btn-box">
              <el-button round v-if="thumbStep === 2" @click="prevStep">上一步</el-button>
            </div>
            <div class="right-btn-box">
              <el-button type="primary" round v-if="thumbStep === 1" :disabled="checkedThumb.length === 0"
                @click="nextStep" :loading="stepLoading">下一步</el-button>
              <template v-else>
                <el-button type="primary" round @click="uploadThumb">确定</el-button>
                <el-button type="" title="跳过剪裁，可能会导致前台图片显示偏差" round @click="cropSkip">跳过</el-button>
              </template>
              <el-button round @click="showThumbBox = false">取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref, computed } from "vue";
import { getRandomString, transBase64FromImage } from "@/utils/tools";
import { fileMd5, singleUpload } from "@/utils/upload";
import { Plus, ZoomOut, ZoomIn, Delete } from '@element-plus/icons-vue';
import { ElMessage } from "element-plus"
import { getEasyImage } from "@/api/file"
import { useStore } from "vuex"
import { getImageSize } from "@/utils/tools"

const store = useStore()
const props = defineProps({
  content: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  value: {
    type: String,
    default: ''
  },
  showForm: {
    type: Boolean,
    default: true
  },
  field: {
    type: String,
    default: ''
  },
  children: {
    type: Array,
    default: () => []
  },
  childrenShow: {
    type: Boolean,
    default: false,
  },
  setting: {
    type: Object,
    default: () => { }
  }
})
const singleActionUrl = ref(store.state.content.singleActionUrl)
const emits = defineEmits(['update:value', 'update:childrenShow'])
const childrenShow = computed(() => props.childrenShow)
const changeChildrenShow = () => {
  emits("update:childrenShow", !childrenShow.value)
}
const content = computed(() => { return props.content })
const grabField = computed(() => {
  const field = store.state.content.fieldList?.find(item => item.field === props.setting.grabfield)
  return field
})
// eslint-disable-next-line vue/return-in-computed-property
const imageScale = computed(() => {
  switch (props.setting.picture_scale) {
    case 1:
      return [16, 9]
    case 2:
      return [3, 4]
  }
})
const handleShowThumbBox = () => {
  thumbList.value = []
  showThumbBox.value = true
  handleMaterial()
  let tinyCnt = content.value
  let imgList = []
  if (tinyCnt) {
    imgList = tinyCnt.match(/<img[^>]+>/g)
  }
  if (imgList && imgList.length > 0) {
    imgList.forEach((item, index) => {
      item.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
        let imgObj = {
          id: index,
          url: capture
        }
        thumbList.value.push(imgObj)
      });
    })
    choseThumb.value = [thumbList.value[0]]
    checkedThumb.value = JSON.parse(JSON.stringify(choseThumb.value))
  }
}
const checkedThumb = ref([])
const showThumbBox = ref(false)
const thumbStep = ref(1)
const thumbSelectMenu = ref(grabField.value ? '1' : '2')
const setAvatarBase64 = (src) => {
  return new Promise((resolve) => {
    let image = new Image();
    // 处理缓存
    image.src = src + "?v=" + Math.random();
    // 支持跨域图片
    image.crossOrigin = "*";
    image.onload = () => {
      let base64 = transBase64FromImage(image);
      resolve(base64);
    };
  });
};
// 图片上传
const maxWidth = computed(() => {
  let currentSite = store.state.site.currentSite
  return currentSite.setting.maxWidth ? currentSite.setting.maxWidth : 2000
})
const imgUploadList = ref([])
const uploadChose = ref([])
const handleBeforeUpload = async (file) => {
  let res = await fileMd5(file)
  if (res.data === false) {
    return true
  } else {
    handleAvatarSuccess(file, res.data.url)
    imgUploadList.value = imgUploadList.value.concat(file)
    return false
  }
}
const handleUpload = async (option) => {
  let data = new FormData()
  data.append('file', option.file)
  // 获取图片文件的宽高属性
  const { width, height, scale } = await getImageSize(option.file, maxWidth.value)
  data.append('cropWidth', width)
  data.append('cropHeight', height)
  data.append('scaledWidth', width)
  data.append('scaledHeight', height)
  data.append('startX', 0)
  data.append('startY', 0)
  data.append('type', 0)
  data.append('path', 'content')
  if (scale < 1) {
    data.append('canMini', true)
  }
  let res = await singleUpload(data, singleActionUrl.value, option.onProgress)
  handleAvatarSuccess(option.file, res.data.url)
}
const handleAvatarSuccess = (file, url) => {
  file.status = 'success'
  file.percentage = 100
  file.url = url
  let _item = {
    id: file.uid,
    url
  }
  imgUploadList.value[0].url = url
  uploadChose.value = [JSON.parse(JSON.stringify(_item))]
  checkedThumb.value = [JSON.parse(JSON.stringify(_item))]
}
const handleChangeFiles = (file) => {
  let URL = null;
  if (window.createObjectURL != undefined) {
    // basic
    URL = window.createObjectURL(file.raw);
  } else if (window.URL != undefined) {
    // mozilla(firefox)
    URL = window.URL.createObjectURL(file.raw);
  } else if (window.webkitURL != undefined) {
    // webkit or chrome
    URL = window.webkitURL.createObjectURL(file.raw);
  }
  file.url = URL
}
const removeUpload = (id) => {
  imgUploadList.value = imgUploadList.value.filter(item => item.uid !== id)
}
const handleExceed = () => {
  ElMessage({
    showClose: true,
    message: '当前只允许上传1张图片',
    type: 'warning'
  })
}
// tab切换
const handleTabChange = (name) => {
  switch (name) {
    case '1':
      checkedThumb.value = JSON.parse(JSON.stringify(choseThumb.value))
      break;
    case '3':
      checkedThumb.value = JSON.parse(JSON.stringify(choseMaterialThumb.value))
      break;
    case '2':
      checkedThumb.value = JSON.parse(JSON.stringify(uploadChose.value))
      break;
  }
}

// 资源切换
const materialImages = ref([])  //资源库图片列表
const defaultMaterialQuery = {
  currentPage: 1,
  pageSize: 10,
  path: 'content',
  type: 0,
  total: 0
}

const materialQuery = reactive(Object.assign({}, defaultMaterialQuery))
const handleGetEasyImage = () => {
  return new Promise((resolve, reject) => {
    getEasyImage(materialQuery).then(res => {
      resolve(res)
      materialImages.value = res.data.list
      materialQuery.total = res.data.total
    }).catch(() => { reject() })
  })
}
const handleMaterialCurrentChange = (page) => {
  materialQuery.currentPage = page
  handleGetEasyImage()
}
const handleMaterial = async () => {
  await handleGetEasyImage()
  choseMaterialThumb.value = [materialImages.value[0]]
}
const choseMaterialThumb = ref([])

const changeLibrary = (e) => {
  if (e.target.classList.contains('btn')) {
    const path = e.target.getAttribute('path')
    Object.assign(materialQuery, defaultMaterialQuery)
    materialQuery.path = path
    handleGetEasyImage()
  }
}
const chooseMaterial = (item) => {
  choseMaterialThumb.value = [item]
  checkedThumb.value = [item]
}


// 正文图片选择
const thumbList = ref([]) //缩略图数组
const choseThumb = ref([])

const handleCloseThumbBox = () => {
  stepLoading.value = false
  imgUploadList.value = []
  checkedThumb.value = []
  thumbStep.value = 1
}
const handleOpenThumbBox = () => {
  if (thumbImg.value) {
    imgUploadList.value.push({
      url: thumbImg.value,
      percentage: 100,
      status: 'success'
    })
    checkedThumb.value = [{
      url: thumbImg.value,
      percentage: 100,
      status: 'success'
    }]
  }
}
const chooseThumb = (item) => {
  choseThumb.value = [item]
  checkedThumb.value = [item]
}
const stepLoading = ref(false)
const nextStep = () => {
  stepLoading.value = true
  setAvatarBase64(checkedThumb.value[0].url).then(base64 => {
    thumbStep.value = 2
    stepLoading.value = false
    option.img = base64
  })
}
const prevStep = () => {
  thumbStep.value = 1
}

//缩略图裁剪
const cropper = ref()
const option = reactive({
  img: '',
  size: 1,
  outputType: 'jpg'
})
const previewImg = reactive({
  img: {},
  url: '',
  div: {},
})
const previewStyle = reactive({
  width: '',
  height: '',
  margin: 0,
  zoom: 1,
  overflow: "hidden"
})
const thumbPreview = (val) => {
  previewImg.img = val.img
  previewImg.url = val.url
  previewImg.div = val.div
  previewStyle.width = val.w + 'px'
  previewStyle.height = val.h + 'px'
  previewStyle.zoom = 90 / val.h
}
const changeScale = (val) => {
  cropper.value.changeScale(val)
}
const thumbImg = computed({
  get: () => {
    return props.value
  },
  set: (val) => {
    emits('update:value', val)
  }
})
const uploadThumb = async () => {
  const { width, height } = cropper.value.cropInfo
  let _fileName = '裁剪图片' + getRandomString(6) + '.jpg'
  cropper.value.getCropBlob(async (blob) => {
    let formData = new FormData()
    // 切割缩略图不分配到资源库，所以不要设置path
    formData.append('name', _fileName)
    formData.append('file', blob)
    formData.append('type', 0)
    formData.append('cropWidth', width)
    formData.append('cropHeight', height)
    formData.append('scaledWidth', width)
    formData.append('scaledHeight', height)
    formData.append('startX', 0)
    formData.append('startY', 0)
    const res = await singleUpload(formData, singleActionUrl.value)
    thumbImg.value = res.data.url
    showThumbBox.value = false
    handleCloseThumbBox()
  })
}
// 跳过
const cropSkip = () => {
  thumbImg.value = imgUploadList.value[0].url
  showThumbBox.value = false
}
const deleteThumb = () => {
  thumbImg.value = ''
}
// 暴露方法
defineExpose({
  handleShowThumbBox,
  deleteThumb
})
</script>
<style scoped lang="scss">
.thumb-img-box {
  border: 1px solid #C4C9D5;
  height: 120px;
  width: 176px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #FFFFFF;
  transition: all 0.3s;
  position: relative;
  margin: 40px 30px 0 0;

  i.no-thumb {
    font-size: 36px;
    color: #AAAAAA;
  }

  img {
    width: 100%;
    height: 100%;
    max-height: 100%;
    max-width: 100%;
  }

  .delete-thumb {
    color: $white;
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    display: none;
    height: 24px;
    width: 24px;
    background-color: #FF5240;
    box-sizing: border-box;
    border: 1px solid rgba(255, 255, 255, 0.5);
    align-items: center;
    justify-content: center;

    i {
      font-size: 16px;
    }
  }

  &:hover {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);

    .delete-thumb {
      display: flex;
    }
  }
}

.thumb-img-box.thumb-img-box-2 {
  height: 120px;
  width: 90px;
}

::v-deep(.thumb-tool-box .el-dialog__body) {
  padding: 0;
}

.thumb-tool-box {
  .image-choose-content {
    .uploader-content {
      .upload-img-box {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        min-height: 300px;

        &>div {
          height: 160px;
          width: 160px;
          margin-right: 20px;
          margin-top: 20px;
          background-color: #F8F8F8;
        }

        &>div:nth-child(5n+1) {
          margin-left: 18px;
        }

        li {
          transition: all 0.3s;
          height: 160px;
          width: 160px;
          box-sizing: border-box;
          list-style: none;
          border: 1px solid #E4E4E4;
          display: flex;
          align-items: center;
          justify-content: center;
          position: relative;
          cursor: pointer;

          .img-box {
            height: 158px;
            width: 158px;
            display: flex;
            justify-content: center;
            align-items: center;

            img {
              max-width: 158px;
              max-height: 158px;
            }
          }

          .progress-box {
            width: 100%;
            position: absolute;
            bottom: 0;

            ::v-deep(.el-progress-bar__outer) {
              border-radius: 0;
            }

            ::v-deep(.el-progress-bar__inner) {
              border-radius: 0;
            }
          }

          .remove-upload {
            color: $white;
            position: absolute;
            right: 5px;
            top: 5px;
            cursor: pointer;
            display: none;
            height: 24px;
            width: 24px;
            background-color: #FF5240;
            box-sizing: border-box;
            border: 1px solid rgba(255, 255, 255, 0.5);
            align-items: center;
            justify-content: center;

            i {
              font-size: 16px;
            }
          }

          &:hover {
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            border-color: $mainColor;
            background-color: $focusContent;

            .remove-upload {
              display: flex;
            }
          }
        }
      }
    }

    .inner-image-choose {
      padding: 0 20px;

      .material-choose-box {
        display: flex;
        margin-bottom: 10px;

        .btn {
          padding: 0 15px;
          line-height: 32px;
          height: 32px;
          border-radius: 100px;
          margin-right: 10px;
          cursor: pointer;
          border: 1px solid #C4C9D5;
        }

        .btn.is-active {
          background-color: $mainColor;
          border-color: $mainColor;
          color: $white;
        }
      }
    }

    h3 {
      font-size: 14px;
      font-weight: normal;
      padding: 10px 0;
    }

    ::v-deep(.el-tabs__item.is-top:nth-child(2)) {
      padding-left: 20px;
    }

    .image-choose-step1 {
      .thumb-list-box {
        display: flex;
        flex-wrap: wrap;

        .thumb-item {
          position: relative;
          height: 160px;
          width: 160px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #F0F2F7;
          margin-right: 15px;
          margin-bottom: 15px;
          box-sizing: border-box;
          cursor: pointer;

          .thumb-item-checkbox {
            position: absolute;
            left: 5px;
            top: 0;

          }

          &.checked {
            border: 1px solid $mainColor;
          }

          &:nth-child(5n) {
            margin-right: 0;
          }

          img {
            max-height: 100%;
            max-width: 100%;
          }
        }
      }
    }

    .image-choose-step2 {
      display: flex;
      padding-top: 24px;
      justify-content: space-between;

      .cropper-box {
        width: 468px;

        .cropper {
          width: 100%;
          height: 430px;
        }

        .cropper-option {
          height: 40px;
          width: 100%;
          border-top: 1px solid #DCDFE6;
          background-color: $backBase;
          display: flex;
          justify-content: center;
          align-items: center;

          .el-icon {
            cursor: pointer;
            font-size: 24px;
          }

          .el-icon:nth-child(1) {
            margin-right: 20px;
          }
        }
      }

      .thumb-preview {
        width: 374px;

        .inner-thumb-preview {
          .thumb-preview-item.big-preview {
            margin-top: 24px;

            .img-box {
              height: 90px;
              width: 160px;
              overflow: hidden;
            }
          }

          .thumb-preview-item.small-preview {
            margin-top: 30px;

            .img-box {
              height: 90px;
              width: 120px;
              overflow: hidden;
            }
          }

          .thumb-preview-item {
            display: flex;
            justify-content: space-between;

            .img-box img {
              max-width: none;
            }

            .img-msg {
              width: 210px;

              p {
                font-size: 14px;
                margin-bottom: 10px;
              }

              span {
                @include tipsText()
              }
            }
          }
        }
      }
    }

    .footer-btn-box {
      padding: 30px 20px;

      .inner-footer {
        display: flex;
        justify-content: space-between;
      }
    }
  }
}

.no-upload-list {
  i {
    color: $mainColor;
  }
}
</style>
